---------------------------------------------------------------
-- @Description：         robot_logic
---------------------------------------------------------------
local skynet = require "skynet"
local CMD = require "game_cmds"
local log = require "sky_log"
local packetbase = require "lua_packetbase"
local socket = require "skynet.socket"
local uu = require "sky_utils"
local gg = require "game_utils"
local cc = require "sky_call"
local game_actions = require "game_actions"
require "def"

local M = {
    --GAME_TYPE必须写，上层需要调用
    --本机器人逻辑支持的对应游戏场
    GAME_TYPE = {
        TABLE_TYPE.TEXAS_NEWCOMER,
        TABLE_TYPE.TEXAS_PRIMARY,
        TABLE_TYPE.TEXAS_MID,
        TABLE_TYPE.TEXAS_ADVANCE,
        TABLE_TYPE.TEXAS_QUICK,
    },
    --定时器运行count计数
    TIME_COUNT = 0,
}

--德州桌子状态
TEXAS_STATE = {
    GAME_STATE_STOP                = 0,
    GAME_STATE_READY               = 1,     --目前来说，此阶段是虚的，和底牌阶段合并在一块了
    GAME_STATE_PREFLOP_ROUND       = 2,
    GAME_STATE_FLOP_ROUND          = 3,
    GAME_STATE_TURN_ROUND          = 4,
    GAME_STATE_RIVER_ROUND         = 5,
    GAME_STATE_ROUND_OVER          = 6,
    GAME_STATE_ROUND_OVERTIMER     = 7,
}
--============================= Local Function =============================--
local function send_msg(fd, msg, size)
    socket.write(fd, msg, size)
end

local function on_login_success(robot, fd, packet)
    local pack = packetbase.create_writebase()
    pack:write_begin(CMD.CLIENT_COMMAND_TABLEINFO_REQUEST)
    pack:write_end()
    
    local msg, size = pack:return_buf()
    send_msg(fd, msg, size)
end

local function on_table_info(robot, fd, packet)
    local table_info = {}

    table_info.game_state = packet:read_byte()
    table_info.max_player = packet:read_byte()
    table_info.game_start_count = packet:read_int()                 --m_GameStartCount
    table_info.dealer_seatid = packet:read_byte()                   --dealer seat
    table_info.current_sit_player_count = packet:read_byte()        --当前有几个坐下的玩家
    table_info.pot_count = packet:read_byte()
    --这里注意要从0开始
    for i=0, table_info.pot_count do
        table_info.pots = {}
        table.insert(table_info.pots, packet:read_int64())
    end

    if table_info.game_state>=TEXAS_STATE.GAME_STATE_FLOP_ROUND
    and table_info.game_state<=TEXAS_STATE.GAME_STATE_RIVER_ROUND then
        --桌面上公共牌数据
        table_info.m_board = {}
        for i=1, table_info.game_state do
            table.insert(table_info.m_board, packet:read_short())
        end
    end

    --有正在下注的座位号时
    table_info.cur_bet_seat = packet:read_short()
    if table_info.cur_bet_seat ~=0 then
        table_info.need_call = packet:read_int64()
        table_info.need_chip = packet:read_int64()
        table_info.max_chip = packet:read_int64()
    end

    local already_sit_t = {}
    table_info.players = {}
    for i=1, table_info.current_sit_player_count do
        local player_detail_t = {}

        player_detail_t.seat_id = packet:read_byte()
        player_detail_t.user_id = packet:read_int()    
        player_detail_t.chips = packet:read_int64()
        player_detail_t.user_name = packet:read_string()
        player_detail_t.icon = packet:read_string()
        player_detail_t.level = packet:read_string()
        player_detail_t.other = packet:read_string()
        player_detail_t.gift = packet:read_string()
        player_detail_t.sit_chips = packet:read_int64()
        player_detail_t.round_chip = packet:read_int64()    --回合下注
        player_detail_t.is_playing  = packet:read_byte()
        player_detail_t.chipin_type = packet:read_byte()

        table_info.players[tonumber(player_detail_t.seat_id)] = player_detail_t
        table.insert(already_sit_t, player_detail_t.seat_id)
    end
    --log.info("table_info=", table_info)
    local sit_pos = uu.boyaa_get_seatid(table_info.max_player, already_sit_t)
    local max_chips = tonumber(robot.config_info.buy_max)
    if  tonumber(robot.db_info.total_money) < tonumber(robot.config_info.buy_max) then
        max_chips = tonumber(robot.db_info.total_money)
    end
    local buy_in = math.random(robot.config_info.buy_min, max_chips)
    log.info("buy_in"..robot.config_info.buy_min.." max_chips "..max_chips)
    log.warning("robot on_player_sitdown: ",  " user_id="..(robot.db_info.id or "nil").." buy_in="..(buy_in or "nil").." sit_pos="..(sit_pos or "nil") 
       .." platid="..(robot.platid or "nil").." svid="..(robot.config_info.svid or "nil").." tid="..(robot.config_info.tid or "nil") )
    
    if sit_pos and buy_in then
        log.info("send sitdown msg!","robot_id="..(robot.db_info.id or "nil").. " sit_pos="..sit_pos.." buy_in="..buy_in)
        robot.game_info = {}
        robot.game_info.user_id = tonumber(robot.db_info.id)
        robot.game_info.platid = tonumber(robot.config_info.platid)
        robot.game_info.tid = tonumber(robot.config_info.tid)
        robot.game_info.svid = tonumber(robot.config_info.svid)
        robot.game_info.followuid = tonumber(robot.followuid)
        robot.game_info.sit_pos = sit_pos 
        robot.game_info.buy_in = buy_in
        robot.game_info.table_info = table_info

        local write_pack = packetbase.create_writebase()
        write_pack:write_begin(CMD.CLIENT_COMMAND_SIT_REQUEST);
        write_pack:write_byte(sit_pos);
        write_pack:write_int64(tonumber(buy_in));
        write_pack:write_int(1)  --是否没筹码自动买入
        write_pack:write_int(0)  --是否最大买入
        write_pack:write_end()
        local msg, size = write_pack:return_buf()
        send_msg(fd, msg, size)
    else
        log.error("robot on_player_sitdown error user_id=", (robot.db_info.id or "nil").." buy_in="..(buy_in or "nil").." sit_pos="..(sit_pos or "nil")
            .." platid="..(robot.platid or "nil").." svid="..(robot.config_info.svid or "nil").." tid="..(robot.config_info.tid or "nil") )
        skynet.send(skynet.self(), "lua", "disconnect_server")
    end
end

local function on_sit_success(robot, fd, packet)
    local robot_info = {}
    robot_info.seat_id = packet:read_byte()
    robot_info.user_name = packet:read_string()
    robot_info.chips = packet:read_int64()
    robot_info.is_real_player = 0
    robot_info.user_id = robot.user_id

    robot.m_seatid = robot_info.seat_id
    robot.table_info.players[robot.m_seatid] = robot_info

    game_actions.init(robot)
end

local function on_broadcast_user_sit(robot, fd, packet)
    if not robot.sit_pos then 
        return
    end
    
    local play_info = {}

    play_info.seat_id = packet:read_byte()
    play_info.user_id = packet:read_int()
    play_info.chips = packet:read_int64()
    play_info.user_name = packet:read_string()
    play_info.icon = packet:read_string()
    play_info.level = packet:read_string()
    play_info.other = packet:read_string()
    play_info.gift = packet:read_string()
    play_info.sit_chips = packet:read_int64()

    robot.table_info.players[tonumber(play_info.seat_id)] = play_info
    
    log.info("on_broadcast_user_sit robot=", robot)
end

--============================= MSG =============================--
--定时器德州和塔尼布机器人暂时都没有用到，所以先在上层屏蔽了，
--后续需要时再开启，这里先留着接口
function M.do_timer()
    M.TIME_COUNT = M.TIME_COUNT + 1
    log.info("robot_logic (agent)[ "..skynet.self().." ] do_timer! count=",M.TIME_COUNT)
end

function M.login_game(robot, fd)
    local pack = packetbase.create_writebase()
    pack:write_begin(CMD.CLIENT_COMMAND_LOGIN)
    pack:write_int(tonumber(robot.config_info.tid))   
    pack:write_int(tonumber(robot.db_info.id))
    --packetbase.write_int(pack, tonumber(robot.db_info.id))  --another type
    pack:write_string(LOGIN_INFO.mtkey)
    pack:write_string("robot")
    pack:write_string("")      --icon
    pack:write_string("10")    --level
    pack:write_string("other")
    pack:write_string("")      --gift
    pack:write_int(0)
    pack:write_string("")
    pack:write_int(0)
    pack:write_int64(0)
    pack:write_int(0)
    pack:write_int(0)
    pack:write_string("")      --passwd
    pack:write_string("")
    pack:write_end()
    
    local msg, size = pack:return_buf()
    send_msg(fd, msg, size)
end

function M.logout_game(robot, fd)
    local write_pack = packetbase.create_writebase()
    write_pack:write_begin(CMD.CLIENT_COMMAND_LOGOUT)
    write_pack:write_end()
    local msg, size = write_pack:return_buf()
    send_msg(fd, msg, size)
end

M.actions = {
    [CMD.SERVER_COMMAND_LOGIN_SUCCESS] = on_login_success,
    [CMD.SERVER_COMMAND_TABLEINFO_RESPONSE] = on_table_info,
    [CMD.SERVER_COMMAND_SIT_SUCCESS] = on_sit_success,
    [CMD.SERVER_BROADCAST_USER_SIT] = on_broadcast_user_sit,
}
setmetatable(M.actions, {__index=game_actions.actions})

return M